import { User ,selectUserField } from "../entity/User";

import { Entity } from "../utils/orm";
import { Service,Inject } from "typedi";
import manager, { DataSource } from "typeorm";
import config from "../config/init";
import { addUser, } from "@/m_req/User";
import { res,JsonResult ,msgList} from "@/utils/jsonResult";
import md5  from "md5";
import  moment  from "moment";
import { User as UserType } from "@/m_res/user";
import  jsonwebtoken  from "jsonwebtoken";
@Service()
export class UserDao{
    @Inject()
    entity!:Entity;

    @Inject()
    json!: JsonResult<any>;

    async GetOneuser(id:number):Promise<res<UserType | null>>{
        
        let data = <UserType> await this.entity.get(User).findOne({
            select: selectUserField,
            where: { user_id: id }
        });

        if (data) {
            return this.json.success(data)
        } else {
            return this.json.success(null,msgList.NoFound)
        }
        
    }


    async addUserDao(params: addUser): Promise<res<null>> {
        let isHave = await this.entity.get(User).findOne({
            where: { "user_name": params.name }
        });
    
        if (isHave != null) {
            return this.json.success(null, msgList.UserNameExist)
        } else {
            await this.entity.source()
            .insert()
            .into(User)
            .values([
                { 
                    user_name: params.name, 
                    user_img: "https://c-ssl.dtstatic.com/uploads/item/202004/29/20200429154321_khaik.thumb.1000_0.jpg",
                    user_pwd: md5(params.pwd),
                    user_type: 0,
                    user_addtime: moment().valueOf()
                },
            ])
            .execute()

            return this.json.success(null, msgList.addUserSuccess)
        }
    }

    async LoginDao(params: addUser): Promise<res<UserType | null>> {
        // const user = await this.entity.get(User).findOneBy({
        //     user_name: params.name,
        //     user_pwd: md5(params.pwd),
        // })

        const user = await this.entity.repository(User)
        .where("user.user_name = :user_name", { user_name: params.name }) 
        .andWhere('user.user_pwd = :user_pwd', { user_pwd: md5(params.pwd) })
        .getOne()
        
        if (user) {
            var token = jsonwebtoken.sign({
                user_id: user.user_id,
                user_name: user.user_name
            }, config.jwtKey);
            return this.json.success(token)
        } else {
            return this.json.error(null,msgList.PasswordError)
        }
    }

    async GetOneUser(id: number): Promise<res<UserType | null>> {
        let data = <UserType>await this.entity.get(User).findOne({
            select: selectUserField,
            where: { user_id: id }
        });
        if (data) {
            return this.json.success(data)
        } else {
            return this.json.success(null,msgList.NoFound)
        }
    }

} 